// 这几个都是ts的数据类型
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

import { getList } from './server';

export interface IndexModelState {
  name: string;
  data: string[];
}

export interface IndexModelType {
  // 如果ts定义不会变的字符串，是可以写死的
  namespace: 'todolist';
  state: IndexModelState;
  effects: {
    loadData: Effect;
  };
  reducers: {
    load: Reducer;
    add: Reducer;
    remove: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  // 命名空间
  namespace: 'todolist',

  // store的数据
  state: {
    name: '',
    data: [],
  },

  // 同步函数
  reducers: {
    load(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    add(state, action) {
      return {
        ...state,
        data: [...state.data, action.payload],
      };
    },
    remove(state, action) {
      return {
        ...state,
        data: state.data.filter((item: string) => item !== action.payload),
      };
    },
  },

  // 异步函数
  effects: {
    *loadData({ payload }, { call, put }) {
      const res = yield call(getList);

      yield put({
        type: 'load',
        payload: res.list,
      });
    },
  },

  // 订阅
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/dva') {
          // 如果打开的页面是/dva，调用loadData异步函数
          dispatch({
            type: 'loadData',
          });
        }
      });
    },
  },
};

export default IndexModel;
